#include <stdlib.h>
#include <string.h>
#include "collaboration.h"
#include "listeningObject.h"

ListeningObject::ListeningObject()
{
	
}

ListeningObject::~ListeningObject()
{
	listeners.clear();
}

int ListeningObject::getListenerPos(const ::std::string& name)
{
	unsigned int i,size;
	size = listeners.size();
	for (i=0; i<size; i++)
	{
		if (listeners[i]->name() == name)
			return i;
	}
	
	return -1;
}

void ListeningObject::addEventListener(EventListener& ev)
{
	if (getListenerPos(ev.name()) == -1) //solo agregar si ya no estaba
	{
		listeners.push_back(&ev);
	}
}

void ListeningObject::removeEventListener(EventListener& ev)
{		
	removeEventListener(ev.name());
}

void ListeningObject::removeEventListener(const ::std::string& name)
{
	int pos = getListenerPos(name);
	if (pos != -1)
	{
		EventListener* aux = listeners[pos];
		listeners[pos] = listeners[listeners.size()-1];
		listeners[listeners.size()-1] = aux;
		
		listeners.pop_back();
		
		delete aux;
	}
}

void ListeningObject::listen(Event& ev)
{	
	unsigned int i,size;
	size = listeners.size();
	for(i=0; i<size; i++)
	{
		if (listeners[i]->checkEvent(ev))
		{
			listeners[i]->action((void*)this, ev);
		}
	}
}
